﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using Controller_Interface.Properties;
using RimbaseLib;
using CPascal.Logging;
using System.Configuration;
using Timers = System.Timers;

namespace Controller_Interface
{
    public partial class ControllerInterfaceForm : Form
    {
        #region - Members

        private NextPositionWatcher _watcher;

        private String _inputFilePathAndName = @"D:\matlaboutput.txt";
        private String _outputFilePathAndName = @"D:\matlaboutput.txt";

        private String _defaultRapidProgram = "/hd0a/testPCM.prg";
        private String _defaultControllerRoot = "/hd0a";

        private String _robotAlias = String.Empty;



        private ListViewItem _oldItem;

        private S4RobTarget _pPosDest;


        private Log _log;
        private LoggInt _loggInt;

        private const String ProcedureWhileName = "MoveToWhile";
        private const String ProcedureProcName = "MoveTo";

        private int _methodID = -1;

        private const String DReady2Name = "ready";
        private const String PPosDestName = "pPosDest";
        private const String CheckPointName = "checkPoint";



        // 2
        private const String FileNameOutputData = "data.pcm";
        private const String FileNameOutputError = "error.pcm";

        //

        long[] timeValuesReturn = new long[100];
        private int indexMain = 0;

        private Stopwatch _swMain;


        //timer

        Timers.Timer aTimer;

        #endregion


        #region  - Constructors

        public ControllerInterfaceForm()
        {
            _pPosDest = null;
            InitializeComponent();

            UpdateFromConfigFile();

            Init();
            aTimer = new Timers.Timer(100);
            aTimer.Elapsed += ATimerElapsed;
            

        }

        #endregion


        #region - Init

        // init config from file
        private void UpdateFromConfigFile()
        {
            _inputFilePathAndName = ConfigurationManager.AppSettings["PathAndNameOfInputFile"];
            _outputFilePathAndName = ConfigurationManager.AppSettings["PathAndNameOfOutputFile"];
            _robotAlias = ConfigurationManager.AppSettings["InterlinkRobotAlias"];
            _defaultRapidProgram = ConfigurationManager.AppSettings["DefaultRapidProgram"];
            _defaultControllerRoot = ConfigurationManager.AppSettings["DefaultControllerRoot"];


            if (AbbControlerHelper.SetControllerName(axInterlinkHelper, _robotAlias))
            {
                gbxInterLink.Visible = false;
            }

            /*
            Console.WriteLine("**** From Config  *******");
            Console.WriteLine("_inputFilePathAndName: " + _inputFilePathAndName);
            Console.WriteLine("_outputFilePathAndName: " + _outputFilePathAndName);
            Console.WriteLine("_robotAlias: " + _robotAlias);
            Console.WriteLine("************************");
             */

        }

        private void Init()
        {
            _watcher = new NextPositionWatcher(_inputFilePathAndName);
            _watcher.RobotPositionChanged += (WatcherRobotPositionChanged);
            _log = new Log(FileNameOutputData, FileNameOutputError);
            _log.LogAppeared += LogLogAppeared;

            _loggInt = new LoggInt();
            _loggInt.LogAppeared += LoggIntLogAppeared;
        }

        void LogLogAppeared(object sender, CPascal.Logging.LogAppearedEventArgs e)
        {
            if (e.Level != 0) return;

            rtbLogView.AppendText(e.Content);
            rtbLogView.AppendText(Environment.NewLine);
        }

        void LoggIntLogAppeared(object sender, LogAppearedEventArgs e)
        {
            rtbLogView.AppendText(e.Content);
            rtbLogView.AppendText(Environment.NewLine);
        }

        #endregion
        

        #region - Handling Events of Log & Watcher

        //event of NextPositionWatcher
        void WatcherRobotPositionChanged(object sender, RobotPositionChangedEventArgs e)
        {
            // se trimite comanda dupa o conditie 
            SelectAndRunMethod(e.Position, e.Orientation);
            UpdateTxtOutput(new[] { e.Position, e.Orientation });
        }

        #endregion


        #region - Handling Events of GUI

        private void ControllerInterfaceFormLoad(object sender, EventArgs e)
        {

            rbtnMethodWhile.Tag = 1;
            rbtnMethodProc.Tag = 2;
            rbtnControllerMotorOn.Tag = 1;
            rbtnControllerMotorOff.Tag = 0;

            InitInterLinkHelper();

            //de mutat
            //if (gbxInterLink.Visible)
            //{
            for (short i = 0; i < axInterlinkHelper.AliasListCount; i++)
            {
                String controllerName = axInterlinkHelper.get_AliasList(i);
                Alias alias = new AliasClass();
                axInterlinkHelper.GetAliasCfg(controllerName, alias);
                var item = new ListViewItem(controllerName);
                item.SubItems.Add(alias.Address);
                item.Tag = controllerName;
                lstControllerView.Items.Add(item);
            }
            //}
            //else
            //{
            //  UseCurrentRobotPosition();
            //}
        }

        private void LstControllerViewDoubleClick(object sender, EventArgs e)
        {

            ListViewItem item = lstControllerView.SelectedItems[0];

            if (item.Tag != null)
            {
                if (_oldItem != null)
                {
                    _oldItem.BackColor = Color.White;
                }
                _oldItem = item;
                _oldItem.Selected = false;
                _oldItem.BackColor = Color.Red;

                AbbControlerHelper.SetControllerName(axInterlinkHelper, (String)item.Tag);
                UseCurrentRobotPosition(0);
            }
        }

        private void BtnUpdateRobotInformationClick(object sender, EventArgs e)
        {
                UseCurrentRobotPosition(0);    
        }

        private void BtnWritePPosDestClick(object sender, EventArgs e)
        {
            SelectAndRunMethod(txt_pPosDestPosition.Text, txt_pPosDestOrientation.Text);
        }

        private void RbtnMethodChangeCheckedChanged(object sender, EventArgs e)
        {
            var radioButton = (RadioButton)sender;
            var tag = (int)radioButton.Tag;

            if (tag == 1)
            {
                if (radioButton.Checked)
                {
                    _methodID = tag;
                    InitMethodWhile();
                }
                else
                {
                    DesposeMethodWhile();
                }
            }

            if (tag == 2)
            {
                if (radioButton.Checked)
                {
                    _methodID = tag;
                }
            }

        }

        private void RbtnControllerMotorCheckedChanged(object sender, EventArgs e)
        {
            var radioButton = (RadioButton)sender;
            var tag = (int)radioButton.Tag;
            if (!radioButton.Checked) return;

            if (tag == 1)
                RunControllerMotors();
            if (tag == 0)
                StopControllerMotors();
        }

        // ok
        private void BtnCopyProgramClick(object sender, EventArgs e)
        {
            var openRapidProgram = new OpenFileDialog
            {
                Title = Resources.RapidProgramFileMsg,
                Filter = Resources.RapidProgramFileClass
            };
            openRapidProgram.ShowDialog();

            if (openRapidProgram.FileName.Equals(String.Empty))
                return;

            var execTime = AbbControlerHelper.CopyProgram(axInterlinkHelper, openRapidProgram.FileName, _defaultControllerRoot, openRapidProgram.FileName);

            if (execTime < 0)
            {
                _loggInt.LogLevelOne(" Error on file copying: ", execTime.ToString());
                return;
            }
            _loggInt.LogLevelOne(" Rapid Program copied  : ", execTime + " ms");
        }

        // ok
        private void BtnLoadProgramClick(object sender, EventArgs e)
        {
            var execTime = AbbControlerHelper.LoadProgram(axInterlinkHelper, _defaultRapidProgram);

            if (execTime < 0)
            {
                _loggInt.LogLevelOne(" Error on Rapid Program loading: ", execTime.ToString());
                return;
            }
            _loggInt.LogLevelOne(" Rapid Program loaded : ", execTime + " ms");

            execTime = AbbControlerHelper.PrepProgram(axInterlinkHelper, "MAIN");

            if (execTime < 0)
            {
                _loggInt.LogLevelOne(" Error on Rapid Program preparing: ", execTime.ToString());
                return;
            }
            _loggInt.LogLevelOne(" Rapid Program prepared : ", execTime + " ms");

        }

        // ok
        private void BtnUnloadProgramClick(object sender, EventArgs e)
        {
            var execTime = AbbControlerHelper.DeleteProgram(axInterlinkHelper);

            if (execTime < 0)
            {
                _loggInt.LogLevelOne(" Error on Rapid Program unloading: ", execTime.ToString());
                return;
            }
            _loggInt.LogLevelOne(" Rapid Program unloaded : ", execTime + " ms");
        }

        // ok 
        private void BtnRunProgramProcedureClick(object sender, EventArgs e)
        {

            var execTime = AbbControlerHelper.RunRapidProcedure(axInterlinkHelper, txtProcedureName.Text);


            if (execTime < 0)
            {
                _loggInt.LogLevelOne(" Error to run " + txtProcedureName.Text + " procedure", execTime.ToString());
                return;
            }
            _loggInt.LogLevelOne(" Procedure " + txtProcedureName.Text + " is running: ", execTime + " ms");
        }
        
  
        private void BtnClearInputClick(object sender, EventArgs e)
        {
            txtOutput.Text = String.Empty;
        }


        private void ControllerInterfaceFormFormClosing(object sender, FormClosingEventArgs e)
        {
            _log.Dispose();
            axInterlinkHelper.Robot = String.Empty;

            //axInterlinkHelper.
            axInterlinkHelper.Dispose();
        }


        private void BtnShowRobotFileManagerClick(object sender, EventArgs e)
        {
            (new RobotFileManager()).Show();
        }

        private void BrnStopRapidProgramClick(object sender, EventArgs e)
        {
            var errorCode = AbbControlerHelper.StopProgram(axInterlinkHelper);
            if (errorCode < 0)
                _log.ToPasiveFile("error", String.Format("{0} {1} {2}", "PrepareRapidProgram", "S4ProgramPrep", errorCode));
        }

        private bool _flagTest = true;

        private void Button5Click(object sender, EventArgs e)
        {

            long errorCode = AbbControlerHelper.SetRapidVar(axInterlinkHelper, "ready", _flagTest);
            _flagTest = !_flagTest;
            if (errorCode < 0)
                _log.ToPasiveFile("error", String.Format("{0} {1} {2}", "PrepareRapidProgram", "S4ProgramPrep", errorCode));
        }

        #endregion


        #region - Updating Methods of GUI

        private void UpdateMonitoringList(String varName, String varValue)
        {

            _log.ToPasiveFile("variableChanged",
                      String.Format("varname: {0}  value: {1}", varName, varValue));


            //modifies the value of the element
            for (int i = 0; i < lvMonitoring.Items.Count; i++)
            {
                var item1 = lvMonitoring.Items[i];
                if (item1.Text.Equals(varName))
                {
                    item1.SubItems[1].Text = varValue;
                    return;
                }
            }

            //adding
            var item = new ListViewItem(varName);
            item.SubItems.Add(varValue);
            lvMonitoring.Items.Add(item);
        }

        private void UpdateCurrentPositionGUI(String position, String orientation)
        {
            txtRobotPosition.Text = position;
            txtRobotOrientation.Text = orientation;
        }

        // de mutat paramentrul S4RobTarget
        private void UpdatePPosDestGui(S4RobTarget posDet)
        {
            txt_pPosDestPosition.Text = ObjectHelper.GetRobTargetPosition(posDet);
            txt_pPosDestOrientation.Text = ObjectHelper.GetRobTargetOrientation(posDet);
        }

        private void UpdateTxtOutput(IEnumerable<string> values)
        {
            BeginInvoke((ThreadStart)delegate
                                         {
                foreach (var s in values)
                {
                    txtOutput.AppendText(s);
                    txtOutput.AppendText(Environment.NewLine);
                }
                txtOutput.AppendText(Environment.NewLine);
            });
        }

        #endregion


        #region # Interlink Helper

        #region - Init Method

        // init interlink helper
        private void InitInterLinkHelper()
        {
            axInterlinkHelper.StatusChanged += AxInterlinkHelperStatusChanged;
            axInterlinkHelper.LogEvent += AxInterlinkHelperLogEvent;
            axInterlinkHelper.VariableChanged += AxInterlinkHelperVariableChanged;
            axInterlinkHelper.NumVariableChanged += AxInterlinkHelperNumVariableChanged;
            axInterlinkHelper.BoolVariableChanged += AxInterlinkHelperBoolVariableChanged;
            axInterlinkHelper.SCWriteEvent += AxInterlinkHelperScWriteEvent;
            //axInterlinkHelper.GenAnalogChanged = true;
            //axInterlinkHelper.GenIOBoardChanged = true;

            //axInterlinkHelper.GenSCWrite = true;



            // changable rapid program
            //var subscriptionList = (S4VariableSubscriptionList)axInterlinkHelper.VariableEventList;

            //subscriptionList.Add(PPosDestName, "robtarget", 0);
            //subscriptionList.Add(CheckPointName, "num", 0);
            //subscriptionList.Add(DReady2Name, "bool", 0);

            
            /*
            INTERLINKLib.ProfileConfigClass profileConfigClass = new ProfileConfigClass();

            Console.WriteLine(profileConfigClass.PollDelay);
            Console.WriteLine(profileConfigClass.ProgFileName);

            INTERLINKLib.ProfileClass profileClass = new ProfileClass();
            //Console.WriteLine(profileClass.ProfileList(0));
            for(short i=0;i<profileClass.ProfileListCount();i++)
                Console.WriteLine(profileClass.ProfileList(i));

            INTERLINKLib.ProfileConfigClass profileConfigClass2 = new ProfileConfigClass(); 

            Object profileobj = new object();

            profileClass.GetProfile("ABBLAB", profileConfigClass2);

            Console.WriteLine(profileConfigClass2.PollDelay);
            
            profileConfigClass2.PollDelay = 200;
            Console.WriteLine("o Valoare");

            Console.WriteLine(profileConfigClass2.PollDelay);

            //profileClass.GetProfile("ABBLAB", profileConfigClass2);

            //Console.WriteLine(profileConfigClass2.PollDelay);
            //Console.WriteLine(profileConfigClass2.ProgFileName);*/
        }

        #endregion

        #region  - Handling InterlinkHelper Events

        // monitorizare variabile: CheckPoint
        private void AxInterlinkHelperNumVariableChanged(object sender, AxRimbaseLib._DHelperEvents_NumVariableChangedEvent e)
        {
            //Console.WriteLine("VariableChanged -- {0} has updated. {1}", e.name, e.newValue);

            //se actualizeaza valoarea variabilei modificate
            //UpdateMonitoringList(e.name, e.newValue.ToString());




            if (e.name.Equals(CheckPointName))
            {
                timeValuesReturn[indexMain] = _swMain.ElapsedMilliseconds;
                indexMain = indexMain + 1;
                _swMain = Stopwatch.StartNew();
            }


            /*
            switch ((int)e.newValue)
            {
                case 0:
                    _log.ToActiveFile(String.Format("{0} method{1} ", axInterlinkHelper.Robot, _methodID),
                                      String.Format(" d0 {0}", (DateTime.Now - _dtStartPerformAction).TotalMilliseconds));
                    break;
                case -1:
                    _log.ToActiveFile(String.Format("{0} method{1} ", axInterlinkHelper.Robot, _methodID),
                                      String.Format(" d1 {0}", (DateTime.Now - _dtStartPerformAction).TotalMilliseconds));



                    // declansarea evenimentului de update    
                    //UseCurrentRobotPosition(0);

                    break;
                case 2: break;
            }*/
        }

        private void AxInterlinkHelperVariableChanged(object sender, AxRimbaseLib._DHelperEvents_VariableChangedEvent e)
        {
            if (_pPosDest == null && e.name.Equals(PPosDestName))
            {
                _pPosDest = (S4RobTarget)e.value;
                UpdatePPosDestGui(_pPosDest);
            }

            //Console.WriteLine("VariableChanged -- {0} has updated. {1}", e.name, e.value);
        }

        private void AxInterlinkHelperBoolVariableChanged(object sender, AxRimbaseLib._DHelperEvents_BoolVariableChangedEvent e)
        {
            UpdateMonitoringList(e.name, e.newValue.ToString());



            /*
            if (e.name.Equals(DReady2Name))
            {

                using (StreamWriter streamWriter = File.CreateText("TEST1.pcm"))
                {


                    foreach (var value in timeValuesReturn)
                    {
                        streamWriter.WriteLine(value);

                    }

                    streamWriter.Close();
                    Console.WriteLine("done");
                }

            }*/

            //Console.WriteLine("VariableChanged -- {0} has updated. {1}", e.name, e.newValue);
        }

        private void AxInterlinkHelperStatusChanged(object sender, AxRimbaseLib._DHelperEvents_StatusChangedEvent e)
        {
            txtControllerState.Text = ControllerState.ResourceManager.GetString("CtlState" + e.ctlState);
            txtOperationalState.Text = ControllerState.ResourceManager.GetString("OprState" + e.ctlState);
            txtProgramControllerState.Text = ControllerState.ResourceManager.GetString("PgmCtlState" + e.ctlState);
            txtProgramState.Text = ControllerState.ResourceManager.GetString("PgmState" + e.ctlState);
        }

        private void AxInterlinkHelperLogEvent(object sender, AxRimbaseLib._DHelperEvents_LogEventEvent e)
        {
            //Console.WriteLine(e.logText);
            _log.ToPasiveFile("error", String.Format("{0}", e.logText));
        }

        private void AxInterlinkHelperScWriteEvent(object sender, AxRimbaseLib._DHelperEvents_SCWriteEventEvent e)
        {
            //not implemented

            //Console.WriteLine("{0}  {1}",e.vname,e.value);
            _log.ToPasiveFile("un mesajjjjjj", String.Format("{0}", ""));
            //throw new NotImplementedException();
        }

        private void AxInterlinkHelperIoChanged(object sender, AxRimbaseLib._DHelperEvents_IOChangedEvent e)
        {
            UpdateMonitoringList(e.signal, e.newValue.ToString());
            _log.ToPasiveFile("IOChanged",
                                  String.Format("signal: {0}  value: {1}", e.signal, e.newValue));
        }

        private void AxInterlinkHelperAnalogChanged(object sender, AxRimbaseLib._DHelperEvents_AnalogChangedEvent e)
        {
            UpdateMonitoringList(e.name, e.newValue.ToString());
            _log.ToPasiveFile("AnalogChanged",
                      String.Format("signal: {0}  value: {1}", e.name, e.newValue));
        }
        
        #endregion

        #endregion


        #region - Rapid Methods
        
        private void SelectAndRunMethod(String position, String orientation)
        {
            if (!position.Equals(String.Empty))
                ObjectHelper.FillRobTargetPosition(_pPosDest, position);

            if (!orientation.Equals(String.Empty))
                ObjectHelper.FillRobTargetOrientation(_pPosDest, orientation);

            switch (_methodID)
            {
                case 1:
                    RunMethodWhile(_pPosDest);
                    break;
                case 2:
                    RunMethodProc(_pPosDest);
                    break;
                default:
                    MessageBox.Show("Selecteaza metoda!");
                    break;
            }
        }

        private void InitMethodWhile()
        {
            long errorCode = AbbControlerHelper.RunRapidProcedure(axInterlinkHelper, ProcedureWhileName);
            if (errorCode < 0)
                _log.ToPasiveFile("error", String.Format("{0} {1} {2}", "InitMethodWhile", "S4Start", errorCode));
        }

        private void RunMethodWhile(S4RobTarget pPosDest)
        {
            long errorCode = AbbControlerHelper.SetRapidVar(axInterlinkHelper, PPosDestName, pPosDest);

            if (errorCode < 0)
                _log.ToPasiveFile("error", String.Format("{0} {1} {2}", "RunMethodWhile", "S4ProgramVariableWrite", errorCode));

            errorCode = AbbControlerHelper.SetRapidVar(axInterlinkHelper, CheckPointName, 1);

            if (errorCode < 0)
                _log.ToPasiveFile("error", String.Format("{0} {1} {2}", "RunMethodWhile", "S4ProgramNumVarWrite", errorCode));
        }

        private void DesposeMethodWhile()
        {
            long errorCode = AbbControlerHelper.SetRapidVar(axInterlinkHelper, DReady2Name, true);

            if (errorCode < 0)
                _log.ToPasiveFile("error", String.Format("{0} {1} {2}", "DesposeMethodWhile", "S4ProgramBoolVarWrite", errorCode));
        }

        private void RunMethodProc(S4RobTarget pPosDest)
        {
            long errorCode = AbbControlerHelper.SetRapidVar(axInterlinkHelper, PPosDestName, pPosDest);

            if (errorCode < 0)
                _log.ToPasiveFile("error", String.Format("{0} {1} {2}", "RunMethodProc", "S4ProgramVariableWrite", errorCode));

            errorCode = AbbControlerHelper.RunRapidProcedure(axInterlinkHelper, ProcedureProcName);

            if (errorCode < 0)
                _log.ToPasiveFile("error", String.Format("{0} {1} {2}", "RunMethodProc", "S4Start", errorCode));
        }

        public void RunControllerMotors()
        {
            var errorCode = AbbControlerHelper.RunMotors(axInterlinkHelper);
            if (errorCode < 0)
                _log.ToPasiveFile("error", String.Format("{0} {1} {2}", "RunControllerMotors", "S4Run", errorCode));
        }

        public void StopControllerMotors()
        {
            var errorCode = AbbControlerHelper.StopMotors(axInterlinkHelper);
            if (errorCode < 0)
                _log.ToPasiveFile("error", String.Format("{0} {1} {2}", "StopControllerMotors", "S4Standby", errorCode));
        }



        private void UseCurrentRobotPosition(int index)
        {            
            var s4RobPosData = new S4RobPosData();

            var exectime = AbbControlerHelper.GetCurrentRobPosData(axInterlinkHelper, s4RobPosData);

            if (exectime<0) 
                return;
            
            Helper.WriteToOutputFile(_outputFilePathAndName, ObjectHelper.GetRotPosDataPositionSimple(s4RobPosData), ObjectHelper.GetRotPosDataOrientationSimple(s4RobPosData));

            // updateGUI
            UpdateCurrentPositionGUI(ObjectHelper.GetRotPosDataPosition(s4RobPosData), ObjectHelper.GetRotPosDataOrientation(s4RobPosData));
        }


        #endregion


        #region - testing


        private void BtnTgetCurrentRobotPositionClick(object sender, EventArgs e)
        {
            var values = new long[200];



            for (var index = 0; index < 200; index++)
            {

                var s4RobPosData = new S4RobPosData();
                    
                var execTime=AbbControlerHelper.GetCurrentRobPosData(axInterlinkHelper, s4RobPosData);

                values[index] = execTime;

                Thread.Sleep(400);
            }

            using (StreamWriter streamWriter = File.CreateText("getcurrentrobotposition.pcm"))
            {

                foreach (var value in values)
                {
                    streamWriter.WriteLine(value);

                }
                streamWriter.Close();
                Console.WriteLine("done");
            }
        }

        private void BtnSetRapidVarS4RobTargetClick(object sender, EventArgs e)
        {
            var timeValues = new long[100];

            S4RobTarget pPosDest = new S4RobTarget();


            for (var index = 0; index < 100; index++)
            {

                var execTime = AbbControlerHelper.SetRapidVar(axInterlinkHelper, PPosDestName, pPosDest);

                timeValues[index] = execTime;

                if (execTime < 0)
                {
                    timeValues[index] = -20;
                }
            }
        }


        private void RtbLogViewDoubleClick(object sender, EventArgs e)
        {
            rtbLogView.Text = String.Empty;
        }


        private void BtnTrunProcedureNtimesClick(object sender, EventArgs e)
        {

            var timeValues = new long[100];

            indexMain = 0;
            _swMain = Stopwatch.StartNew();

            for (var index = 0; index < 100; index++)
            {

                long errorCode = 0;

                Stopwatch sw = Stopwatch.StartNew();

                errorCode = AbbControlerHelper.RunRapidProcedure(axInterlinkHelper, txtProcedureName.Text);

                timeValues[index] = sw.ElapsedMilliseconds;
                //Console.WriteLine(valueTime);

                if (errorCode < 0)
                    //_log.ToPasiveFile("error", String.Format("{0} {1} {2}", "PrepareRapidProgram", "S4ProgramLoad", errorCode));
                    //Console.WriteLine("error :: " + errorCode);
                    timeValues[index] = -20;

                Thread.Sleep(50);
            }


            using (StreamWriter streamWriter = File.CreateText("checkPoint.pcm"))
            {

                foreach (var value in timeValues)
                {
                    streamWriter.WriteLine(value);

                }

                streamWriter.WriteLine();

                foreach (var value in timeValuesReturn)
                {
                    streamWriter.WriteLine(value);

                }

                streamWriter.Close();
                Console.WriteLine("done");

            }

        }

        private void BtnTest1Click(object sender, EventArgs e)
        {

            indexMain = 0;
            _swMain = Stopwatch.StartNew();

            long errorCode = 0;

            errorCode = AbbControlerHelper.RunRapidProcedure(axInterlinkHelper, txtProcedureName.Text);
            if (errorCode < 0)
                Console.WriteLine("error :: " + errorCode);



/*           using (StreamWriter streamWriter = File.CreateText("TEST1.pcm"))
            {


                foreach (var value in timeValuesReturn)
                {
                    streamWriter.WriteLine(value);

                }

                streamWriter.Close();
                Console.WriteLine("done");

            }*/
        }


        private void BtnTreadVarIntClick2(object sender, EventArgs e)
        {


            //var timeValues = new long[10000];
            //var varValues = new float[10000];


            var timeReadValue = new List<long>();
            var parameterValue = new List<float>();

            var index = 0;


            long errorCode = AbbControlerHelper.RunRapidProcedure(axInterlinkHelper, "TEST1");
            if (errorCode < 0)
                Console.WriteLine("error :: " + errorCode);


            float valueRead = 0;
            while (valueRead < 100 && index < 10000)
            {


                
                long executionTime = AbbControlerHelper.GetRapidVar(axInterlinkHelper, CheckPointName, ref valueRead);

                parameterValue.Add(valueRead);
                timeReadValue.Add(executionTime);
                
                Thread.Sleep(20);
                index++;
            }


            //remove first values
            timeReadValue.RemoveAt(0);
            parameterValue.RemoveAt(0);


            using (StreamWriter streamWriter = File.CreateText("checkPointReadValue.pcm"))
            {

                foreach (var value in timeReadValue)
                {
                    streamWriter.WriteLine(value);

                }

                streamWriter.WriteLine();

                foreach (var value in parameterValue)
                {
                    streamWriter.WriteLine(value);

                }

                streamWriter.Close();
                Console.WriteLine("done");

            }
        }

        private void BtnTwriteVarIntClick(object sender, EventArgs e)
        {
            WriteVariableInWhile();

        }

        private  void WriteVariable()
        {
            var timeToWriteFloatValue = new List<long>();

            var varToWrite = 100;


            AbbControlerHelper.RunRapidProcedure(axInterlinkHelper, "TEST2");

            for (var index = 0; index <= 200; index++)
            {
                long executionTime = AbbControlerHelper.SetRapidVar(axInterlinkHelper, CheckPointName, varToWrite);

                timeToWriteFloatValue.Add(executionTime);
                varToWrite++;
            }


            using (StreamWriter streamWriter = File.CreateText("timeToWriteAFloatValue.pcm"))
            {

                foreach (var value in timeToWriteFloatValue)
                {
                    streamWriter.WriteLine(value);

                }

                streamWriter.Close();
                Console.WriteLine("done");

            }
        }

        private void WriteVariableInWhile()
        {

            const String inputValueName = "inputValue";
            const String changeNumberName = "changeNumber";
            float changeNumberValue = 0;
            
            var timeToWriteFloatValue = new List<long>();

            var varToWrite = 1;

            AbbControlerHelper.RunRapidProcedure(axInterlinkHelper, "TEST2");

            Thread.Sleep(1000);

            for (var index = 0; index <= 200; index++)
            {
                long executionTime = AbbControlerHelper.SetRapidVar(axInterlinkHelper, inputValueName, varToWrite);

                timeToWriteFloatValue.Add(executionTime);
                varToWrite++;
            }

            long aaa= AbbControlerHelper.GetRapidVar(axInterlinkHelper, changeNumberName, ref changeNumberValue);
            Console.WriteLine(aaa);

            using (var streamWriter = File.CreateText("timeToWriteAFloatValueWhile.pcm"))
            {

                foreach (var value in timeToWriteFloatValue)
                {
                    streamWriter.WriteLine(value);

                }

                streamWriter.WriteLine();
                streamWriter.WriteLine();

                streamWriter.WriteLine(changeNumberValue);

                streamWriter.Close();
                Console.WriteLine("done");

            }
        }


        private void ReadRobtargetInWhile()
        {


            var timeReadValue = new List<long>();
            const string objectName = "pPosDest";

            for (var index = 0; index <= 100;index++)
            {
                var valueRead = new S4RobTarget();
                var executionTime = AbbControlerHelper.GetRapidVar(axInterlinkHelper, objectName, ref valueRead);
                timeReadValue.Add(executionTime);
            }

            using (StreamWriter streamWriter = File.CreateText("ReadRobtargetValue.pcm"))
            {

                foreach (var value in timeReadValue)
                {
                    streamWriter.WriteLine(value);

                }

                streamWriter.Close();
                Console.WriteLine("done");

            }


        }

        private void WriteRobtargetVar()
        {
            string position = "[387.7842,-756.519,1236.31]";
            string orientation = "[0.000502791,-0.9623058,-0.2719696,0.0006773844]";
            var timeWriteValue = new List<long>();
            var timeToFillRobTarget = new List<long>();
            const string objectName = "pPosDest";
            var pPosDest = new S4RobTarget();
            
            
            var executionTime = AbbControlerHelper.GetRapidVar(axInterlinkHelper, objectName, ref pPosDest);
            Console.WriteLine(executionTime);


            for(var index = 0; index <= 100;index++)
            {
                var executionTime1 = ObjectHelper.FillRobTargetVar(pPosDest, position, orientation);
                var executionTime2 = AbbControlerHelper.SetRapidVar(axInterlinkHelper, objectName, pPosDest);
                timeToFillRobTarget.Add(executionTime1);
                timeWriteValue.Add(executionTime2);
            }

            
            
            timeWriteValue.RemoveAt(0);

            
            using (StreamWriter streamWriter = File.CreateText("WriteRobtargetValue.pcm"))
            {

                foreach (var value in timeWriteValue)
                {
                    streamWriter.WriteLine(value);

                }

                streamWriter.WriteLine();
                streamWriter.WriteLine();


                foreach (var value in timeToFillRobTarget)
                {
                    streamWriter.WriteLine(value);
                }

                streamWriter.Close();
                Console.WriteLine("done");

            }

        }

        private void BtnTreadRapidObjectClick(object sender, EventArgs e)
        {
            ReadRobtargetInWhile();
        }

        private void BtnTwriteRobTargetClick(object sender, EventArgs e)
        {
            WriteRobtargetVar();
        }


        private void RunWhileRapidMethod2()
        {
            var timeValueRead = new List<long>();
            var timeValueMethod = new List<long>();
            var timeWriteValue = new List<long>();
            string position = "[387.7842,-756.519,1236.31]";
            string orientation = "[0.000502791,-0.9623058,-0.2719696,0.0006773844]";
            const string objectName = "pPosDest";


            long executiontime1 = AbbControlerHelper.RunRapidProcedure(axInterlinkHelper, "RUNWHILE");

            var pPosDest = new S4RobTarget();


            var executionTime = AbbControlerHelper.GetRapidVar(axInterlinkHelper, objectName, ref pPosDest);

            if (executiontime1<0)
            {
                Console.WriteLine("eroare runwhile");
                return;
            }

            float execNo = 0;
            AbbControlerHelper.SetRapidVar(axInterlinkHelper, "execNo", execNo);


            long executiontime6 = 0;
            long executiontime7 = 0;

            for (var index = 0; index <= 200; index++)
            {

                //Console.WriteLine("intra 23");
                var stopwatch = Stopwatch.StartNew();

                float checkPoint = 0;
                ObjectHelper.FillRobTargetVar(pPosDest, position, orientation);
                AbbControlerHelper.SetRapidVar(axInterlinkHelper, objectName, pPosDest);
                var executiontime10 = AbbControlerHelper.SetRapidVar(axInterlinkHelper, "checkPoint", checkPoint);
                var executiontime2 = AbbControlerHelper.SetRapidVar(axInterlinkHelper, "update", 1);

                if (index == 0)
                {
                    executiontime6 = executiontime10;
                    executiontime7 = executiontime2;
                }
                    

                checkPoint = 0;
                //polling end of task
                while (!checkPoint.Equals(100))
                {
                    AbbControlerHelper.ReadRapidVar(axInterlinkHelper, CheckPointName, ref checkPoint);
                }
                long executiontime3 = stopwatch.ElapsedMilliseconds;
                timeValueMethod.Add(executiontime3);


            }

            Console.WriteLine("index 0 {0}{1}",executiontime6,executiontime7);

            execNo = 0;
            AbbControlerHelper.GetRapidVar(axInterlinkHelper, "execNo", ref execNo);


            using (StreamWriter streamWriter = File.CreateText("runwhileRapidMethod.pcm"))
            {

                foreach (var value in timeValueMethod)
                {
                    streamWriter.WriteLine(value);
                }
                streamWriter.WriteLine();
                streamWriter.WriteLine();

                foreach (var value in timeValueRead)
                {
                    streamWriter.WriteLine(value);
                }
                streamWriter.WriteLine();
                streamWriter.WriteLine();
                streamWriter.WriteLine(executiontime1);
                streamWriter.WriteLine();
                streamWriter.WriteLine();
                streamWriter.WriteLine(execNo);

                streamWriter.Close();
            }

            AbbControlerHelper.SetRapidVar(axInterlinkHelper, "exitWhile", true);
            Console.WriteLine("done");

        }


        //init 
        private long InitRunWhile(S4RobTarget pPosDest, float execNo)
        {
            const string objectName = "pPosDest";
            const string methodName = "RUNWHILE";
            const string execNoName = "execNo";
            const string updateName = "update";
            const float updateValue = 0;

            var executionTime = AbbControlerHelper.GetRapidVar(axInterlinkHelper, objectName, ref pPosDest);
            if (executionTime < 0)
                return executionTime;

            executionTime = AbbControlerHelper.SetRapidVar(axInterlinkHelper,execNoName, execNo);
            if (executionTime < 0)
                return executionTime;

            executionTime = AbbControlerHelper.SetRapidVar(axInterlinkHelper, updateName, updateValue);
            if (executionTime < 0)
                return executionTime;

            executionTime = AbbControlerHelper.RunRapidProcedure(axInterlinkHelper, methodName);
            if (executionTime < 0)
                return executionTime;

            return 0;
        }


        List<long> _timeValueMethod = new List<long>();
        List<long> _timeUpdate = new List<long>();
        S4RobTarget _pPosDesteExt = new S4RobTarget();
        private int _steps = 100;

        private long MoveToTask(S4RobTarget pPosDest, string position, string orientation, float taskID)
        {
            var stopwatch = Stopwatch.StartNew();
            const string objectName = "pPosDest";
            const string updateName = "update";
            const float updateValue = 1;

            ObjectHelper.FillRobTargetVar(pPosDest, position, orientation);
            AbbControlerHelper.SetRapidVar(axInterlinkHelper, objectName, pPosDest);
            AbbControlerHelper.SetRapidVar(axInterlinkHelper, "taskID", 1);
            AbbControlerHelper.SetRapidVar(axInterlinkHelper, updateName, updateValue);

            _timeUpdate.Add(stopwatch.ElapsedMilliseconds);

            //polling the task ending
            float checkPoint = 0;
            while (!checkPoint.Equals(100))
            {
                AbbControlerHelper.ReadRapidVar(axInterlinkHelper, CheckPointName, ref checkPoint);
            }

            return stopwatch.ElapsedMilliseconds;
        }

        void ATimerElapsed(object sender, Timers.ElapsedEventArgs e)
        {
            
            
            const string position = "[387.7842,-756.519,1236.31]";
            const string orientation = "[0.000502791,-0.9623058,-0.2719696,0.0006773844]";

            if (_steps > 0)
            {

                var executiontime3 = MoveToTask(_pPosDesteExt, position, orientation, 1);
                _timeValueMethod.Add(executiontime3);
                _steps--;
                return;
            }

            aTimer.Enabled = false;
            
            float execNo = 0;
            AbbControlerHelper.GetRapidVar(axInterlinkHelper, "execNo", ref execNo);

            PrintToFile(_timeValueMethod, _timeUpdate, execNo, "test2_method_runwhile.pcm");


            BeginInvoke((ThreadStart)delegate
            {
                _loggInt.LogLevelOne("Test 2 ended", "execNo: " + execNo);
            });
            
            
        }

        private void RunWhileRapidMethod3()
        {
            var pPosDest = new S4RobTarget();


            float execNo = 0;


            // init 
            long returnValue = InitRunWhile(pPosDest, execNo);

            if (returnValue < 0)
            {
                Console.WriteLine("Error on the rapid method 'RUNWHILE' initialization: {0}", returnValue);
                return;
            }
            
            _pPosDesteExt = pPosDest;
            _timeValueMethod = new List<long>();
            _timeUpdate = new List<long>();
            _steps = 300;
            aTimer.Interval = 50; //100 ms
            aTimer.Enabled = true;
        }


        private void RunWhileRapidMethod()
        {
            //var timeValueRead = new List<long>();
            var timeValueMethod = new List<long>();

            const string position = "[387.7842,-756.519,1236.31]";
            const string orientation = "[0.000502791,-0.9623058,-0.2719696,0.0006773844]";

            var pPosDest = new S4RobTarget();


            float execNo = 0;


            // init 
            long returnValue = InitRunWhile(pPosDest, execNo);

            if (returnValue < 0){

                Console.WriteLine("Error on the rapid method 'RUNWHILE' initialization: {0}",returnValue);
                return;
            }

            // execution 

            for (var index = 0; index <= 100; index++)
            {
                var executiontime3 = MoveToTask(pPosDest, position, orientation, 1);
                timeValueMethod.Add(executiontime3);
            }

            execNo = 0;
            AbbControlerHelper.GetRapidVar(axInterlinkHelper, "execNo", ref execNo);


            using (StreamWriter streamWriter = File.CreateText("runwhileRapidMethod.pcm"))
            {

                foreach (var value in timeValueMethod)
                {
                    streamWriter.WriteLine(value);
                }
                streamWriter.WriteLine();
                streamWriter.WriteLine();

                streamWriter.WriteLine(execNo);

                streamWriter.Close();
            }

            AbbControlerHelper.SetRapidVar(axInterlinkHelper, "exitWhile", true);
            Console.WriteLine("done");

        }
        
        
        private void RunRapidMethod()
        {
            var timeValueRead = new List<long>();

            long executiontime1 = AbbControlerHelper.RunRapidProcedure(axInterlinkHelper, "RUN");

            float checkPoint = 0;



            var stopwatch = Stopwatch.StartNew();
            while (!checkPoint.Equals(100))
            {
                long executionTime2 = AbbControlerHelper.GetRapidVar(axInterlinkHelper, CheckPointName, ref checkPoint);
                timeValueRead.Add(executionTime2);
            }
            long executiontime3 = stopwatch.ElapsedMilliseconds;

            
            using (StreamWriter streamWriter = File.CreateText("runRapidMethod.pcm"))
            {

                foreach (var value in timeValueRead)
                {
                    streamWriter.WriteLine(value);
                }
                streamWriter.WriteLine();
                streamWriter.WriteLine();
                streamWriter.WriteLine(executiontime1);
                streamWriter.WriteLine();
                streamWriter.WriteLine();
                streamWriter.WriteLine(executiontime3);

                streamWriter.Close();
            }

            Console.WriteLine("done");

        }

        private void BtnRunMethodClick(object sender, EventArgs e)
        {
            RunRapidMethod();
            
        }

        private void BtnRunWhileMethodClick(object sender, EventArgs e)
        {
            RunWhileRapidMethod3();
        }

        private void BtnRunWhileClick(object sender, EventArgs e)
        {
            _timeValueMethod = new List<long>();
            _timeUpdate = new List<long>();
            
            var pPosDest = new S4RobTarget();
            float execNo = 0;

            // init
            var stopwatch = Stopwatch.StartNew();
            var error = InitRunWhile(pPosDest, execNo);
            var execTime = stopwatch.ElapsedMilliseconds;
            _pPosDesteExt = pPosDest;

            if (error < 0)
            {
                _loggInt.LogLevelOne(" Error on runwhile initialization: ", error.ToString());
                return;
            }
            _loggInt.LogLevelOne(" RunWhile Rapid method inited: ", execTime + " ms");
            _loggInt.LogLevelOne(" RunWhile Rapid method is running ... ","");
           
        }

        private void BtnStopRunWhileClick(object sender, EventArgs e)
        {
            var execTime = AbbControlerHelper.SetRapidVar(axInterlinkHelper, "exitWhile", true);


            if (execTime < 0)
            {
                _loggInt.LogLevelOne(" Error on runwhile initialization: ", execTime.ToString());
                return;
            }
            _loggInt.LogLevelOne(" RunWhile Rapid method stopped: ", execTime + " ms");
        }

        private static void PrintToFile(List<long> lst1, List<long> lst2, float execNo, string fileName)
        {
          
            using (var streamWriter = File.CreateText(fileName))
            {

                foreach (var value in lst1)
                {
                    streamWriter.WriteLine(value);
                }
                streamWriter.WriteLine();
                streamWriter.WriteLine();

                foreach (var value in lst2)
                {
                    streamWriter.WriteLine(value);
                }

                streamWriter.WriteLine();
                streamWriter.WriteLine();

                streamWriter.WriteLine(execNo);

                streamWriter.Close();
            }
        }
        
        private void BtnTestRunWhile1Click(object sender, EventArgs e)
        {
            _timeValueMethod = new List<long>();
            _timeUpdate = new List<long>();

            const string position = "[387.7842,-756.519,1236.31]";
            const string orientation = "[0.000502791,-0.9623058,-0.2719696,0.0006773844]";

            var steps = 0;

            if(!int.TryParse(txtSteps.Text,out steps))
            {
                return;
            }

            _loggInt.LogLevelOne("Test 1 started","");


            
            for(var index=0;index<steps;index++)
            {
                var executiontime3 = MoveToTask(_pPosDesteExt, position, orientation, 1);
                _timeValueMethod.Add(executiontime3);
            }

            

            float execNo = 0;
            AbbControlerHelper.GetRapidVar(axInterlinkHelper, "execNo", ref execNo);

            PrintToFile(_timeValueMethod, _timeUpdate, execNo, "test1_method_runwhile.pcm");
            _loggInt.LogLevelOne("Test 1 ended", "execNo: " + execNo);

        }

        private void BtnTestRunWhile2Click(object sender, EventArgs e)
        {
            if (!int.TryParse(txtSteps.Text, out _steps))
            {
                return;
            }

            int interval;
            if (!int.TryParse(txtInterval.Text, out interval))
            {
                return;
            }
            
            _timeValueMethod = new List<long>();
            _timeUpdate = new List<long>();
            aTimer.Interval = interval; //100 ms

            _loggInt.LogLevelOne("Test 2 started", "");
            aTimer.Enabled = true;
        }

        #endregion


    }
}
